package com.zhou.controller;

import com.zhou.static_dao.ProviderDao;
import com.zhou.entities.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 供应商的控制层
 */
@Controller
public class ProviderController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProviderDao providerDao;
    //这是采用jdbc的方式去操作数据库的，用了mybatis就不用这个了

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/jdbc/providers")
    public Map<String, Object> jdbc(Map<String, Object> map){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM provider");
        return list.get(0);
    }

    @GetMapping("/provider")
    public String list(Map<String, Object> map
            , @RequestParam(value = "providerName", required = false) String providerName){
        logger.info("供应商列表查询。。。。。"+providerName);
        Collection<Provider> providers = providerDao.getAll(providerName);
        map.put("providers",providers);
        map.put("providerName",providerName);
        return "provider/list";
    }

    @GetMapping("/provider/{id}")
    public String view(Map<String, Object> map, @PathVariable("id") Integer id
            , @RequestParam(value = "type", defaultValue =  "view") String type){
        logger.info("供应商查看。。。。。"+id);
        Provider provider = providerDao.getProvider(id);
        map.put("provider",provider);
        if ("update".equals(type)){
            return "provider/update";
        } else if ("view".equals(type)){
            return "provider/view";
        } else {
            providerDao.delete(id);
            return "provider/list";
        }
    }

    @PutMapping("/provider")
    public String submitUpdate(Provider provider){
        logger.info("供应商修改。。。。。");
        providerDao.save(provider);
        return "redirect:/provider";
    }

    @GetMapping("/provider/add")
    public String add(){
        logger.info("供应商添加。。。。。");
        return "provider/add";
    }
    @PostMapping("/provider")
    public String submitAdd(Provider provider){
        logger.info("供应商添加。。。。。");
        providerDao.save(provider);
        return "redirect:/provider";
    }

    @DeleteMapping("/provider/{id}")
    public String delete(@PathVariable("id") Integer id){
        logger.info("供应商删除。。。。。");
        providerDao.delete(id);
        return "redirect:/provider";
    }

}
